package edu.uwm.cs552;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Iterator;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;


public class CityDialog extends JDialog {
	/**
	 * Keep Eclipse happy.
	 */
	private static final long serialVersionUID = 1L;

	private static final int NUM_CHOICES = 2;
	
	private JTextField nameField = new JTextField(10);
	private JComboBox[] goodChoices;
	
	private City city = null;
	
	public CityDialog(JFrame frame) {
		super(frame, "City Info",true);
		JPanel namePanel = new JPanel();
		namePanel.add(new JLabel("Name:"));
		namePanel.add(nameField);
		getContentPane().setLayout(new GridLayout(NUM_CHOICES+2,1));
		getContentPane().add(namePanel);
		goodChoices = new JComboBox[NUM_CHOICES];
		for (int i=0; i < NUM_CHOICES; ++i) {
			goodChoices[i] = new GoodComboBox();
			getContentPane().add(goodChoices[i]);
		}
		JPanel buttonPanel = new JPanel();
		JButton OKbutton = new JButton("OK");
		JButton cancelButton = new JButton("Cancel");
		buttonPanel.add(OKbutton);
		buttonPanel.add(cancelButton);
		getContentPane().add(buttonPanel);
		OKbutton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				ok();
			}
		});
		cancelButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				cancel();
			}
		});
		setSize(200,200);
	}
	
	public void open(City c) {
		if (c != null) {
			nameField.setText(c.getName());
			Iterator<Good> it = c.iterator();
			for (JComboBox cb : goodChoices) {
				if (it.hasNext()) {
					cb.setSelectedItem(it.next());
				} else {
					cb.setSelectedItem(null);
				}
			}
		}
		setVisible(true);
	}
	private void ok() {
		city = new City(nameField.getText());
		nameField.setText("");
		for (JComboBox cb : goodChoices) {
			Good g = (Good)cb.getSelectedItem();
			if (g != null) city.addGood(g);
		}
		setVisible(false);
	}
	
	private void cancel() {
		city = null;
		setVisible(false);
	}
	
	public City getCity() {
		return city;
	}
}
